<?php
/**
 * @package qBase
 * @subpackage base
 */

/**
 * QInit initializes the entire qBase solution
 * @package qBase
 * @subpackage base
 */
final class QBaseInit extends QObject 
{
	/**
	 * The runtime variables
	 *
	 * @var array
	 */
	protected static $RuntimeVars = array();
	/**
	 * True if the runtime variables have changed
	 * If so will save the vars on shutdown
	 *
	 * @var boolean
	 */
	protected static $RuntimeVarsChanged = false;
	
	private static $RuntimeVarsFile = null;
	/**
	 * Call this function to initializa qBase 
	 *
	 */
	public static function Init()
	{
		QAutoload::AddWatchFolder(__QBasePath, false, false);

		set_error_handler(array("QErrorHandler", "HandleError"), E_ALL);
		register_shutdown_function(array("QBaseInit", "OnShutdown"));
		
		// test accept header
		/*
		$req_uri = $_SERVER['REQUEST_URI'];
		if ($req_uri)
		{
			$pos = strrpos($req_uri, ".");
			if ($pos !== false)
			{
				// var_dump($req_uri);
				// header("HTTP/1.0 404 Not Found");
				// die();
			}
		}
		*/
	}
	
	public static function SetRuntimeFile($file)
	{
		if (!file_exists($file))
		{
			$dir = dirname($file);
			if (!is_dir($dir))
				mkdir($dir, 0755, true);
			file_put_contents($file, "<?php\n\n?>");
		}
		self::$RuntimeVarsFile = $file;
		require_once(self::$RuntimeVarsFile);
	}
	
	public static function OnShutdown()
	{
		if (self::$RuntimeVarsFile)
		{
			// cleanup when need
			$now = time();
			$last = self::GetRuntimeVar("LastCleanupTime");
			
			if ($last)
			{
				// cleanup every N sec
				if (($now - $last) > QWebApp::$ClenupInterval)
				{
					// do cleanup
					QWebApp::DoCleanup();
					self::SetRuntimeVar("LastCleanupTime", $now);
				}
			}
			else 
				self::SetRuntimeVar("LastCleanupTime", $now);
				
			if (self::$RuntimeVarsChanged)	
			{
				// save the variables
				$str = "<?php\n\n";
				
				foreach (self::$RuntimeVars as $key => $var)
				{
					$str .= "\tQBaseInit::SetRuntimeVar(\"".addslashes($key)."\", ";
					if (is_null($var))
						$str .= "null";
					else if (is_string($var))
						$str .= "\"".addslashes($var)."\"";
					else if (is_bool($var))
					{
						if ($var)
							$str .= "true";
						else 
							$str .= "false";
					}
					else if (is_scalar($var))
						$str .= $var;
					else 
						throw new Exception("Unsupported variable type for: {$key}");
						
					$str .= ", false);\n";
				}
				
				$str .= "\n?>";
				
				file_put_contents(self::$RuntimeVarsFile, $str);
			}
		}
		
		QErrorHandler::OnShutdown();
	}
	
	/**
	 * Gets the elapsed time in seconds (with fractions) since the script has started
	 *
	 * @param integer $round How many fractions to get
	 * @return float
	 */
	public static function GetElapsedTime($round = 4)
	{
		if (!defined("__SCRIPT_START_FLOAT"))
			throw new Exception("__SCRIPT_START_FLOAT is not defined");
		list($usec, $sec) = explode(' ', microtime());
		$script_end = (float) $sec + (float) $usec;

		
		if (!is_null($round))
			return round($script_end - __SCRIPT_START_FLOAT, $round);
		else 
			return ($script_end - __SCRIPT_START_FLOAT);
	}
	
	/**
	 * Prints the elapsed time in seconds (with fractions) since the script has started 
	 *
	 * @param integer $round How many fractions to get
	 * @param boolean $stop_script If true will end the execution
	 */
	public static function PrintElapsedTime($round = 4, $stop_script = false)
	{
		echo "<p id='QBaseInit_PrintElapsedTime' style='position: fixed; bottom: 0px; left: 0px; font-size: 11px;'>Generated in: ".(
			self::GetElapsedTime($round))." sec</p>";
			
		if ($stop_script)
		{
			die();
		}
	}
	
	/**
	 * Sets a runtime variable
	 * Runtime variables are set per application and are saved when the script ends if there were any changes
	 *
	 * @param string $key
	 * @param scalar $value
	 */
	public static function SetRuntimeVar($key, $value, $set_change_status = true)
	{
		if (!is_scalar($value))
			throw new Exception("The value of a runtime variable must be a scalar");
		self::$RuntimeVars[$key] = $value;
		if ($set_change_status)
			self::$RuntimeVarsChanged = true;
	}
	
	/**
	 * Gets a runtime variable
	 *
	 * @param string $key
	 * @return scalar
	 */
	public static function GetRuntimeVar($key)
	{
		if (isset(self::$RuntimeVars[$key]))
			return self::$RuntimeVars[$key];
		else 
			return null;
	}
	
	/**
	 * Returns the path of the framework
	 *
	 * @return string
	 */
	public static function GetFrameworkPath()
	{
		return __QBasePath;
	}
}


?>